package e3dcs

import (
	"time"

	"gitee.com/ameise84/e3dcs/internal/discov"
	"gitee.com/ameise84/e3dcs/internal/message"
	"gitee.com/ameise84/e3dcs/internal/rpc"
)

func init() {
	rpc.SetMsgOnRecvFunc(Post)
}

func RegisterNetService(name string, fac ActorAdapterFactory, msgSize int32) (NetService, error) {
	opts := DefaultServiceOptions()
	opts.SetMode(BLModePoll)
	opts.SetMsgSize(msgSize)
	return _gRouterProvider.register(name, fac, opts)
}

func RegisterRpcService(name string, fac ActorAdapterFactory, opts *ServiceOptions) (RpcService, error) {
	return _gRouterProvider.register(name, fac, opts)
}

func Start(opts *DcsOptions) (err error) {
	message.SetCallSlowDuration(time.Duration(opts.callSlow) * time.Second)
	_gCallTimeOut = time.Duration(opts.callTimeOut) * time.Second
	//启动服务与发现
	if err = discov.Start(opts.discoOptions); err != nil {
		return err
	}
	defer func() {
		if err != nil {
			discov.Stop()
		}
	}()
	//启动rpc服务
	var rpcAddr string
	if rpcAddr, err = rpc.Start(opts.rpcOptions); err != nil {
		return err
	}
	defer func() {
		if err != nil {
			rpc.Stop()
		}
	}()
	//启动本地服务展厅
	return _gRouterProvider.start(rpcAddr)
}

func Stop() {
	_gRouterProvider.stop()
	rpc.Stop()
	discov.Stop()
}

func Post(msg *message.Message) {
	_gRouterProvider.post(msg)
}

func FreeResponse(rsp message.Response) {
	message.FreeMessage(rsp.(*message.Message))
}
